package cn.francis.filter;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfedu.agro.util.JwtUtil;
import com.qfedu.agro.vo.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Name: JwtAuthenticationTokenFilter
 * Package: cn.francis.filter
 * Date: 2024/10/26 - 09:58
 * Description: 身份验证过滤器
 *
 * @author Junhui Zhang
 * @version v1.0
 */

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if (token == null || token.trim().isEmpty()) {
            filterChain.doFilter(request, response);
            return;
        }
        // TODO 验证token
        JwtUtil jwtUtil = new JwtUtil();
        Claims claims = jwtUtil.parseJWT(token);
        String id = (String) claims.get("id");
        String jsonLoginUser = redisTemplate.opsForValue().get("login:" + id);
        if (StrUtil.isBlank(jsonLoginUser)) {
            filterChain.doFilter(request,response);
            return;
        }
        LoginUser loginUser = new ObjectMapper().readValue(jsonLoginUser, LoginUser.class);
        UsernamePasswordAuthenticationToken token1 =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(token1);
        // 延长有效期时长
        redisTemplate.expire("login:" + id, 1800, TimeUnit.SECONDS);
        filterChain.doFilter(request, response);
    }
}
